package com.base.api.pms.impl;

import com.alibaba.fastjson.JSONObject;
import com.base.api.pms.PmsPublicSqlQuery;
import com.base.api.pms.PmsSqlQueryService;
import com.base.dao.pms.PmsSqlQueryMapper;
import com.base.utils.ApplicationContextGetBeanHelper;
import com.base.vo.pms.PmsSqlQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@CacheConfig(cacheNames = {"pms"})
public class PmsSqlQueryServiceImpl implements PmsSqlQueryService {

    @Autowired
    private PmsSqlQueryMapper pmsSqlQueryMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Map<String, Object> ExcetorQueryByCode(String code, Map<String, Object> param) throws ClassNotFoundException {
        if (code == null) {
            throw new RuntimeException("传入的查询类名为空！");
        }
        PmsSqlQuery pmsSqlQuery = getPmsSqlQueryByCode(code);
        if (pmsSqlQuery == null) {
            throw new RuntimeException("根据类名找不到对应的sqlquery！" + code);
        }
        PmsPublicSqlQuery publicSqlQuery = (PmsPublicSqlQuery) ApplicationContextGetBeanHelper.getBean(pmsSqlQuery.getCode());
        Map<String, Object> map;
        if (param.get("PageRequest") == null) {
            map = publicSqlQuery.ExecuteQuery(pmsSqlQuery.getSqlText(), (Map<String, Object>) param.get("params"));
        } else {
            map = publicSqlQuery.ExecuteQueryByPageHelper(pmsSqlQuery.getSqlText(), param);
        }
        return map;
    }

    private PmsSqlQuery getPmsSqlQueryByCode(String code) {
        if (code == null) {
            throw new RuntimeException("传入的类名为空！请检查！" );
        }
        String key = "pms::getPmsSqlQueryByCode[" + Arrays.toString(new String[]{code}) + "]";
        if (stringRedisTemplate.hasKey(key)) {
            return JSONObject.parseObject(stringRedisTemplate.opsForValue().get(key), PmsSqlQuery.class);
        } else {
            PmsSqlQuery pmsSqlQuery = pmsSqlQueryMapper.selectByCode(code);
            if (pmsSqlQuery == null) {
                throw new RuntimeException("根据类名找不到对应的sqlquery！" + code);
            }
            stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(pmsSqlQuery));
            return pmsSqlQuery;
        }
    }

    /**
     * 执行查询接口
     *
     * @param param 参数
     * @return
     */
    @Override
    public String Query(Map<String, Object> param) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.putAll(ExcetorQueryByCode((String) (param.get("code")), param));
            map.put("code", "0");
        } catch (Exception e) {
            map.put("code", "error");
            map.put("msg", "处理异常,"+e.getMessage());
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 模糊查询
     * @param params
     * @return
     */
    @Override
    public String getSqlQueryByKeywords(Map<String,Object> params) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("data", pmsSqlQueryMapper.selectByKeyward((String) (params.get("KeyWords"))));
            map.put("code", 0);
        } catch (Exception e) {
            map.put("code", "error");
            map.put("msg", e.getMessage());
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 精确查询
     * @param params
     * @return
     */
    @Override
    public String getSqlQueryByCode(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("data",getPmsSqlQueryByCode((String) (params.get("code"))));
            map.put("code", "0");
        } catch (Exception e) {
            map.put("code", "error");
            map.put("msg", e.getMessage());
        }
        return JSONObject.toJSONString(map);
    }

    /**
     * 修改保存
     * @param pmsSqlQuery
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    /**
     * 修改之后，一把清缓存
     */
    public String saveSqlQuery(PmsSqlQuery pmsSqlQuery) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (pmsSqlQuery.getId() == null) {
                pmsSqlQuery.setCreateDate(new Date());
                pmsSqlQueryMapper.insertSelective(pmsSqlQuery);
            } else {
                pmsSqlQuery.setModifyDate(new Date());
                pmsSqlQueryMapper.updateByPrimaryKeyWithBLOBs(pmsSqlQuery);
            }
            map.put("code", 0);
        } catch (Exception e) {
            map.put("code", "error");
            map.put("msg", e.getMessage());
        }
        return JSONObject.toJSONString(map);
    }
}
